﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using WCrawlerLib;

namespace WCrawler
{
    public partial class ImagesManagement : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                txtUrl.Text = @"http://i276.photobucket.com/albums/kk15/hgtuan2003/FunPics/vui1.jpg";
        }

        /// <summary>
        /// Solution 1
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public bool getImageByUrl(string url, string filename)
        {
            WebResponse response = null;
            Stream remoteStream = null;
            StreamReader readStream = null;
            try
            {
                WebRequest request = WebRequest.Create(url);
                if (request != null)
                {
                    response = request.GetResponse();
                    if (response != null)
                    {
                        remoteStream = response.GetResponseStream();

                        readStream = new StreamReader(remoteStream);

                        System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);

                        if (img == null)
                            return false;

                        // YOUR CODE HERE: make manipulations with the image object
                        

                        // save image to disk
                        img.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
                        img.Dispose();
                    }
                }
            }
            finally
            {
                if (response != null) response.Close();
                if (remoteStream != null) remoteStream.Close();
                if (readStream != null) readStream.Close();
            }

            return true;
        }

        /// <summary>
        /// Solution 2
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        /// <param name="imageType"></param>
        /// <returns></returns>
        public static bool saveImageByUrlToDisk(string url, string filename)
        {
            string imageType = "";
            WebResponse response = null;
            Stream remoteStream = null;
            StreamReader readStream = null;
            try
            {
                WebRequest request = WebRequest.Create(url);
                if (request != null)
                {
                    response = request.GetResponse();
                    if (response != null)
                    {
                        remoteStream = response.GetResponseStream();
                        // analyze image type, image extension
                        string content_type = response.Headers["Content-type"];
                        imageType = content_type;
                        if (content_type == "image/jpeg" || content_type == "image/jpg")
                        {
                            imageType = "jpg";
                        }
                        else if (content_type == "image/png")
                        {
                            imageType = "png";
                        }
                        else if (content_type == "image/gif")
                        {
                            imageType = "gif";
                        }
                        else
                        {
                            imageType = "";
                            return false;
                        }

                        readStream = new StreamReader(remoteStream);
                        Stream fw = File.Open(filename, FileMode.Create);
                        //
                        byte[] buf = new byte[256];
                        int count = remoteStream.Read(buf, 0, 256);
                        while (count > 0)
                        {
                            fw.Write(buf, 0, count);
                            count = remoteStream.Read(buf, 0, 256);
                        }

                        fw.Close();
                    }
                }
            }
            finally
            {
                if (response != null) response.Close();
                if (remoteStream != null) remoteStream.Close();
            }

            return true;
        }

        public void ResizeImage(string imagePath)
        {
            string pathAvatars = Server.MapPath("~/");
            try
            {
                int thumbWidth = 100;
                int thumbHeight = 75;
                System.Drawing.Image oImg =  System.Drawing.Image.FromFile(imagePath);
                System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                oGraphic.DrawImage(oImg, oRectangle);

                oThumbNail.Save(pathAvatars + "\\Avatar.jpg", ImageFormat.Jpeg);
                oImg.Dispose();
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string imageName = "";
            string localurl = "";
            string hosturl = txtUrl.Text;
            //string url = @"http://img576.imageshack.us/img576/553/imtoomoviemaker450.gif";
            //string url = @"http://cyberwarez.info/forum/images/logo.jpg";
            //string url = @"http://i1.ambrybox.com/250411/1303679501828.jpeg";
            //string url = @"http://i276.photobucket.com/albums/kk15/hgtuan2003/FunPics/vui1.jpg";

            string[] split = hosturl.Split(new char[] { '/' });
            imageName = split[split.Count() - 1];
            localurl = "Images/" + imageName;
            //save to disk
            saveImageByUrlToDisk(txtUrl.Text, Server.MapPath(localurl));
            //PostImage obj = new PostImage();
            //obj.Insert(imageName, hosturl, localurl);
            GridView1.DataBind();
        }
    }
}